// 正币
window.onload = function () {
    let limit_net_id = 97;
    let refresh_num = 0;
    let user_address;
    let web3;
    let token_abi_url = "/static/home/contract/token_abi.json";
    let connect_address = "";//当前钱包地址
    let lp_balance_show = 0;
    let lp_balance_show1 = 0;
    let isLoginStatus = 0;

    setTimeout(function (){
        if(typeof window.ethereum !== 'undefined'){
            console.log("web3实例")
            web3 = new Web3(window.ethereum);//web3js就是你需要的web3实例
        }else{
            console.log("web3实例")
            web3 = new Web3(Web3.givenProvider);//web3js就是你需要的web3实例
        }
        if(web3 != undefined){
            init();
        }else{
            layer.msg('钱包丢失了');
        }
    },500)

    // 初始化
    function init(){
        window.ethereum.enable().catch(function(reason){
        }).then(function(accounts){
            web3.eth.net.getId().then((net_id)=>{
                if(net_id != limit_net_id){
                    layer.msg('只支持币安链');
                    return;
                }
                if(typeof accounts == undefined || accounts[0] == ''){
                    refresh_num += 1;
                    if(refresh_num < 6){
                        setTimeout(function (){
                            init();
                        },1000);
                        return;
                    }else{
                        layer.msg('授权登陆失败，请稍后再试...');
                        return;
                    }
                }else{
                    refresh_num = 0;
                }
                login(accounts[0])
            });
        });
    }

    // 去登陆
    function login(address) {
        user_address = address
        console.log('登陆地址=',address);
    }


    function changeLpBalance() {
        if(connect_address == ''){
            return;
        }
        $.ajax({
            type:'post',
            url:"/home/Index/changeLpBalance",
            data:{address:connect_address},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    $(".all_lp_amount").html(res.data.all_lp_amount);
                    $(".lp_amount").html(res.data.lp_amount);
                    $(".lp_rate span").html(res.data.lp_rate);
                }
            },
            error: function(e){
            },
        });
    }

    function getWallet(){
        if(typeof connect_address != 'undefined' && connect_address != ''){
            $.ajax({
                type:'post',
                url:"/home/Index/getWallet",
                data:{address:connect_address},
                dataType:'json',
                success:function(res){
                    if(res.status == 1){
                        getPimLp()
                    }
                },
                error: function(e){
                },
            });
        }
    }

    function getPimLp() {
        if(typeof connect_address != 'undefined' && connect_address != ''){
            $.ajax({
                type:'post',
                url:"/home/Index/getPimLp",
                data:{address:connect_address},
                dataType:'json',
                success:function(res){
                    if(res.status == 1){
                        $(".all_lp_amount").html(res.data.all_lp_amount);
                        $(".cash_token_aomunt").html(res.data.cash_token_aomunt);
                        $(".lp_amount").html(res.data.lp_amount);
                        $(".lp_rate span").html(res.data.lp_rate);
                        $(".my_all_bonus").html(res.data.my_all_bonus);
                        $(".my_today_bonus").html(res.data.my_today_bonus);
                        $(".pool_all").html(res.data.pool_all);
                        $(".today_all_bonus").html(res.data.today_all_bonus);
                        $(".token_amount").html(res.data.token_amount);
                        setInterval(function () {
                            changeLpBalance();
                        },30000);
                    }
                },
                error: function(e){
                },
            });
        }
    }

    function showHidePage(type) {
        $(".login_page").hide()
        $(".van-overlay").hide()
        $(".van-popup--left").hide()
        $(".cash_page").hide()
        $(".pledge_page").hide()
        $(".rele_pledge_page").hide()
        if(type == 1){//left
            $(".van-overlay").show()
            $(".van-popup--left").show()
        }else if(type == 2){//登录弹窗
            $(".van-overlay").show()
            $(".login_page").show()
        }else if(type == 3){//提现
            $(".van-overlay").show()
            $(".cash_page").show()
        }else if(type == 4){//质押
            $(".van-overlay").show()
            $(".pledge_page").show()
        }else if(type == 5){//解押
            $(".van-overlay").show()
            $(".rele_pledge_page").show()
        }
    }

    function show_login(){
        $(".nologin_show").hide()
        $(".login_show").show()
    }
    function show_nologin(){
        $(".nologin_show").show()
        $(".login_show").hide()
    }

    //连接钱包
    $(".connectWallet").click(function () {
        window.location.href = "/";
    });
    //挖矿详情
    $(".node").click(function () {
        window.location.href ="/home/index/profit?address="+connect_address;
    });
    // 质押/解押详情
    $(".pledge_log").click(function () {
        window.location.href ="/home/Pledge/logPage?address="+connect_address;
    });
    //提取列表
    $(".cashList").click(function () {
        window.location.href ="/home/Cash/logPage?address="+connect_address;
    });

    //点击左边
    $(".icosn").click(function () {
        showHidePage(1)
    });
    $(".auth_user").click(function () {
        console.log("user_address=",user_address);
        showHidePage(2)
    });
    $(".van-overlay").click(function () {
        showHidePage(0)
    });
    $("#cash").click(function () {
        showHidePage(3)
    });
    $(".cashSubmit").click(function () {
        var token_num = $("#token_num").val();
        if(typeof connect_address == 'undefined' || connect_address == ''){
            err_tip('请先链接钱包')
            return;
        }
        if(token_num == '' || token_num <= 0){
            err_tip('请先输入提取数量');
            return;
        }
        $(this).hide();
        $(".cashSubmiting").show();
        $.ajax({
            type:'post',
            url:"/home/Index/cash",
            data:{address:connect_address,token_num:token_num},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    success_tip('成功')
                    setTimeout(function () {
                        window.location.href = "/";
                    },1000);
                }else{
                    err_tip(res.msg);
                    $(".cashSubmit").show();
                    $(".cashSubmiting").hide();
                }
            },
            error: function(e){
                $(".cashSubmit").show();
                $(".cashSubmiting").hide();
            },
        });
    });

    function isLogin() {
        $.ajax({
            type:'post',
            url:"/home/Index/isLogin",
            data:{address:connect_address},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    isLoginStatus = 1;
                }else{
                    isLoginStatus = 0;
                    accountVerify(res.data)
                }
            }
        });
    }

    function accountVerify(sign_msg){
        web3.eth.personal.sign(sign_msg,connect_address,(err, signature) => {
            if(typeof signature != 'undefined' && signature != ''){
                $.ajax({
                    type:'post',
                    url:"/home/Index/accountVerify",
                    data:{address:connect_address,sign_msg:sign_msg,signature:signature},
                    dataType:'json',
                    success:function(res){
                        if(res.status == 1){
                            isLoginStatus = 1;
                        }else{
                            isLoginStatus = 0;
                        }
                    },
                });
            }
        });
    }

    //质押
    $("#pledge_btn").click(function (){
        console.log('user_address',user_address);
        showHidePage(4);
        $.ajax({
            type:'post',
            url:"/home/Index/lpBalance",
            data:{address:connect_address},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    lp_balance_show = res.data;
                    $("#lp_balance_show font").html(res.data);
                }else{
                    err_tip(res.msg)
                }
            },
            error: function(e){
                err_tip('fail')
            },
        });
    });

    //解押
    $("#rele_pledge_btn").click(function () {
        isLogin();
        showHidePage(5);
        $.ajax({
            type:'post',
            url:"/home/Index/lpBalance1",
            data:{address:connect_address},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    lp_balance_show1 = res.data;
                    $("#lp_balance_show1 font").html(res.data);
                }else{
                    err_tip(res.msg)
                }
            },
            error: function(e){
                err_tip('fail')
            },
        });
    });

    //全部解押
    $(".allRelePledgeSubmit").click(function () {
        if(isLoginStatus != 1){
            err_tip('解押失败，您无此权限');
            setTimeout(function () {
                window.location.reload()
            },1500);
            return;
        }
        var lp_num = lp_balance_show1;
        if(lp_num <= 0 || lp_balance_show1 < lp_num){
            err_tip('当前可解押数量不足');
            return;
        }

        layer.confirm('确认要全部解押吗？', {
            btn : ['确定', '取消']
            // 按钮
        }, function() {
            relePeldgeShow(1)
            layer.closeAll('dialog');
            $.ajax({
                type:'post',
                url:"/home/Index/relePledgeAction",
                data:{address:connect_address,lp_num:lp_num},
                dataType:'json',
                success:function(res){
                    if(res.status == 1){
                        err_tip(res.msg)
                        setTimeout(function () {
                            window.location.reload()
                        },1500);
                    }else{
                        err_tip(res.msg)
                        relePeldgeShow(0)
                    }
                },
                error: function(e){
                    relePeldgeShow(0)
                },
            });
        });
    });

    function relePeldgeShow(type){
        $(".allRelePledgeSubmit").hide();
        $(".relePledgeSubmiting").hide();
        $(".relePledgeSubmit").hide();
        if(type == 1){
            $(".relePledgeSubmiting").show();
        }else{
            $(".allRelePledgeSubmit").show();
            $(".relePledgeSubmit").show();
        }
    }

    //解押
    $(".relePledgeSubmit").click(function () {
        if(isLoginStatus != 1){
            err_tip('解押失败，您无此权限');
            setTimeout(function () {
                window.location.reload()
            },1500);
            return;
        }
        var lp_num = $("#rele_pledge_num").val();
        relePeldgeShow(1)
        $.ajax({
            type:'post',
            url:"/home/Index/relePledgeAction",
            data:{address:connect_address,lp_num:lp_num},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    err_tip(res.msg)
                    setTimeout(function () {
                        window.location.reload()
                    },1500);
                }else{
                    err_tip(res.msg)
                    relePeldgeShow(0)
                }
            },
            error: function(e){
                relePeldgeShow(0)
            },
        });
    });

    function peldgeShow(type){
        $(".allPledgeSubmit").hide();
        $(".pledgeSubmiting").hide();
        $(".pledgeSubmit").hide();
        if(type == 1){
            $(".pledgeSubmiting").show();
        }else{
            $(".pledgeSubmit").show();
            $(".allPledgeSubmit").show();
        }
    }

    //全部质押
    $(".allPledgeSubmit").click(function () {
        var lp_num = lp_balance_show;
        if(lp_num <= 0 || lp_balance_show < lp_num){
            err_tip('当前可质押数量不足');
            return;
        }

        layer.confirm('确认要全部质押吗？', {
            btn : ['确定', '取消']
            // 按钮
        }, function() {
            peldgeShow(1)
            layer.closeAll('dialog');
            $.getJSON(token_abi_url,function(contractAbi){
                $.ajax({
                    type:'post',
                    url:"/home/Index/checkPledgeData",
                    data:{address:connect_address,lp_num:lp_num},
                    dataType:'json',
                    success:function(res){
                        if(res.status == 1){
                            var tokenContract = new web3.eth.Contract(contractAbi, res.data.lp_contract_address, {
                                from: connect_address,
                            });
                            // 代币转账
                            tokenContract.methods.transfer(res.data.plat_lp_wallet_address, res.data.amount.toString()).send({from: connect_address}, function(error, transactionHash){
                                if(!error) {
                                    console.log('transactionHash is ' + transactionHash);
                                    pledgeSubmit(connect_address,res.data.lp_num,transactionHash)
                                } else {
                                    console.log(error);
                                    err_tip(error)
                                    peldgeShow(0)
                                }
                            })
                        }else{
                            err_tip(res.msg)
                            peldgeShow(0)
                        }
                    },
                    error: function(e){
                        peldgeShow(0)
                    },
                });
            });
        });
    });

    //质押
    $(".pledgeSubmit").click(function () {
        var lp_num = $("#pledge_num").val();
        if(lp_num <= 0 || lp_balance_show < lp_num){
            err_tip('当前可质押数量不足');
            return;
        }
        peldgeShow(1)
        $.getJSON(token_abi_url,function(contractAbi){
            $.ajax({
                type:'post',
                url:"/home/Index/checkPledgeData",
                data:{address:connect_address,lp_num:lp_num},
                dataType:'json',
                success:function(res){
                    if(res.status == 1){
                        var tokenContract = new web3.eth.Contract(contractAbi, res.data.lp_contract_address, {
                            from: connect_address,
                        });
                        // 代币转账
                        tokenContract.methods.transfer(res.data.plat_lp_wallet_address, res.data.amount.toString()).send({from: connect_address}, function(error, transactionHash){
                            if(!error) {
                                console.log('transactionHash is ' + transactionHash);
                                pledgeSubmit(connect_address,res.data.lp_num,transactionHash)
                            } else {
                                console.log(error);
                                err_tip(error)
                                peldgeShow(0)
                            }
                        })
                    }else{
                        err_tip(res.msg)
                        peldgeShow(0)
                    }
                },
                error: function(e){
                    peldgeShow(0)
                },
            });

        });
    });

    function pledgeSubmit(address,lp_num,txid) {
        $.ajax({
            type:'post',
            url:"/home/Index/pledgeAction",
            data:{address:address,lp_num:lp_num,txid:txid},
            dataType:'json',
            success:function(res){
                if(res.status == 1){
                    success_tip(res.msg)
                    setTimeout(function () {
                        window.location.href = "/";
                    },1000);
                }else{
                    err_tip(res.msg)
                    peldgeShow(0)
                }
            },
            error: function(e){
                peldgeShow(0)
            },
        });
    }

    function err_tip(msg) {
        $("#tip").html(msg);
        $("#tip").show().delay(3000).fadeOut();
    }
    function success_tip(msg) {
        $("#success_tip").html(msg);
        $("#success_tip").show().delay(3000).fadeOut();
    }


}





